<?php

namespace app\api\controller;

use app\api\Api;
use think\captcha\Captcha;
use think\Db;

class System extends Api
{
    /**
     * 获取所有错误代码
     *
     * @return void
     */
    public function errors()
    {
        $codeList = [];
        foreach ($GLOBALS['API_CODE_GLOBAL'] as $k => $v) {
            $codeList[] = $v;
        }
        return jok(null, $codeList);
    }

    /**
     * 获取图片验证码
     *
     * @return void
     */
    public function getCaptcha()
    {
        $captcha = new Captcha();
        return jok('success', $captcha->entryApi());
    }
    /**
     * 不允许生成的节点
     *
     * @var array
     */
    protected $controllerBackList = ["auth", "conf", "error", "group", "index", "log", "login", "logout", "node", "tool", "user", "system", "attach", "sms", "base", "wechat"];

    /**
     * 代码生成主逻辑
     *
     * @return void
     */
    public function build()
    {
        //走AccessToken验证
        $error = $this->auth();
        if ($error) {
            return $error;
        }
        //走Rbac验证
        $error = $this->rbac();
        if ($error) {
            return $error;
        }
        $table = strtolower(input("code_controller"));
        if (empty($table)) {
            return jerr("请输入控制器名称");
            exit;
        }
        if (empty(input("code_title"))) {
            return jerr("请输入节点名称");
            exit;
        }
        if (in_array($table, $this->controllerBackList)) {
            return jerr("代码生成失败，请重新指定控制器名");
            exit;
        }
        $this->postBlackList = [$table . '_id', $table . '_status', $table . '_createtime', $table . '_updatetime'];
        // print_r($_POST);die;
        if (input("c_table") == "true") {
            //创建表开始
            $sql = "CREATE TABLE `" . config('database.prefix') . $table . "` (`" . $table . "_id` INT(9) NOT NULL AUTO_INCREMENT ";
            foreach ($_POST['fieldList'] as $field) {
                if (empty($field['field_name'])) {
                    continue;
                } else {
                    $field['field_name'] = preg_replace("/[^a-z,A-Z]/", "", $field['field_name']);
                }
                if (empty($field['field_datatype'])) {
                    $field['field_datatype'] = 'varchar';
                } else {
                    $field['field_datatype'] = preg_replace("/[^a-z,A-Z]/", "", $field['field_datatype']);
                }
                if (empty($field['field_length'])) {
                    $field['field_length'] = '255';
                } else {
                    $field['field_length'] = preg_replace("/[^0-9,\,]/", "", $field['field_length']);
                }
                if (empty($field['field_desc'])) {
                    $field['field_desc'] = $field['field_name'];
                }
                switch (strtolower($field['field_datatype'])) {
                    case 'text':
                    case 'longtext':
                        $sql .= " ,`" . $table . "_" . strtolower($field['field_name']) . "` " . $field['field_datatype'] . " NULL DEFAULT NULL";
                        break;
                    case 'int':
                    case 'bigint':
                    case 'tinyint':
                    case 'double':
                    case 'float':
                    case 'decimal':
                        if (isset($field['field_default']) && is_numeric($field['field_default'])) {
                            //整数 已设置默认值
                            $sql .= " ,`" . $table . "_" . strtolower($field['field_name']) . "` " . $field['field_datatype'] . "(" . $field['field_length'] . ")" . " NOT NULL DEFAULT '" . $field['field_default'] . "'";
                        } else {
                            $sql .= " ,`" . $table . "_" . strtolower($field['field_name']) . "` " . $field['field_datatype'] . "(" . $field['field_length'] . ")" . " NOT NULL DEFAULT 0";
                        }
                        break;
                    default:
                        if (isset($field['field_default']) && strtolower($field['field_default']) != "null" && strtolower($field['field_default']) != '') {
                            //整数 已设置默认值
                            $sql .= " ,`" . $table . "_" . strtolower($field['field_name']) . "` " . $field['field_datatype'] . "(" . $field['field_length'] . ")" . " NOT NULL DEFAULT '" . $field['field_default'] . "'";
                        } else {
                            $sql .= " ,`" . $table . "_" . strtolower($field['field_name']) . "` " . $field['field_datatype'] . "(" . $field['field_length'] . ")" . " NOT NULL DEFAULT ''";
                        }
                        break;
                }
                if (isset($field['field_desc'])) {
                    $sql .= " comment '" . $field['field_desc'] . "'";
                }
            }
            $sql .= " ,`" . $table . "_status` INT(9) NOT NULL DEFAULT '0' comment '状态'";
            $sql .= " ,`" . $table . "_createtime` INT(9) NOT NULL DEFAULT '0' comment '创建时间'";
            $sql .= " ,`" . $table . "_updatetime` INT(9) NOT NULL DEFAULT '0' comment '修改时间'";
            $sql .= " , PRIMARY KEY (`" . $table . "_id`)) ENGINE = InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='" . input("code_title") . "表'";
            try {
                $result = Db::execute($sql);
            } catch (\Exception $e) {
                return jerr($e->getMessage());
            }
            //创建表结束
        }
        if (input("c_node") == "true") {
            $data = [
                "node_title" => "获取" . input("code_title") . "详情接口",
                "node_controller" => $table,
                "node_action" => "detail",
                "node_pid" => 4,
                "node_show" => 1,
                "node_createtime" => time(),
                "node_updatetime" => time(),
            ];
            db("node")->insert($data);
            $data = [
                "node_title" => "添加" . input("code_title") . "接口",
                "node_controller" => $table,
                "node_action" => "add",
                "node_pid" => 4,
                "node_show" => 1,
                "node_createtime" => time(),
                "node_updatetime" => time(),
            ];
            db("node")->insert($data);
            $data = [
                "node_title" => "修改" . input("code_title") . "接口",
                "node_controller" => $table,
                "node_action" => "update",
                "node_pid" => 4,
                "node_show" => 1,
                "node_createtime" => time(),
                "node_updatetime" => time(),
            ];
            db("node")->insert($data);
            $data = [
                "node_title" => "删除" . input("code_title") . "接口",
                "node_controller" => $table,
                "node_action" => "delete",
                "node_pid" => 4,
                "node_show" => 1,
                "node_createtime" => time(),
                "node_updatetime" => time(),
            ];
            db("node")->insert($data);
            $data = [
                "node_title" => "禁用" . input("code_title") . "接口",
                "node_controller" => $table,
                "node_action" => "disable",
                "node_pid" => 4,
                "node_show" => 1,
                "node_createtime" => time(),
                "node_updatetime" => time(),
            ];
            db("node")->insert($data);
            $data = [
                "node_title" => "启用" . input("code_title") . "接口",
                "node_controller" => $table,
                "node_action" => "enable",
                "node_pid" => 4,
                "node_show" => 1,
                "node_createtime" => time(),
                "node_updatetime" => time(),
            ];
            db("node")->insert($data);
            $data = [
                "node_title" => "获取" . input("code_title") . "列表接口",
                "node_controller" => $table,
                "node_action" => "lists",
                "node_pid" => 4,
                "node_show" => 1,
                "node_createtime" => time(),
                "node_updatetime" => time(),
            ];
            db("node")->insert($data);
            $data = [
                "node_title" => "" . input("code_title") . "管理",
                "node_module"=>"admin",
                "node_controller" => $table,
                "node_action" => "index",
                "node_pid" => 0,
                "node_show" => 1,
                "node_createtime" => time(),
                "node_updatetime" => time(),
            ];
            db("node")->insert($data);
        }
        if (input("c_controller") == "true") {
            //开始生成index
            $url = "application/admin/.templateController";
            $file = file_get_contents($url);
            $file = str_replace("TMP_controller", ucfirst($table), $file);
            $file = str_replace("tmp_controller", $table, $file);
            $myfile = fopen("application/admin/controller/" . ucfirst($table) . ".php", "w") or die("Unable to open file!");
            fwrite($myfile, $file);
            fclose($myfile);
        }

        if (input("c_api") == "true") {
            //开始生成index
            $url = "application/admin/.templateApi";
            $file = file_get_contents($url);
            $file = str_replace("TMP_controller", ucfirst($table), $file);
            $file = str_replace("tmp_controller", $table, $file);
            $myfile = fopen("application/api/controller/" . ucfirst($table) . ".php", "w") or die("Unable to open file!");
            fwrite($myfile, $file);
            fclose($myfile);
        }
        if (input("c_model") == "true") {
            //开始生成index
            $url = "application/admin/.templateModel";
            $file = file_get_contents($url);
            $file = str_replace("TMP_controller", ucfirst($table), $file);
            $file = str_replace("tmp_controller", $table, $file);
            $myfile = fopen("application/model/" . ucfirst($table) . ".php", "w") or die("Unable to open file!");
            fwrite($myfile, $file);
            fclose($myfile);
        }

        if (input("c_view") == "true") {
            if (!is_dir("application/admin/view/" . $table)) {
                mkdir("application/admin/view/" . $table, 0777, true);
            }
            //开始生成index
            $url = "application/admin/.templateIndex";
            //echo $url;exit;
            $file = file_get_contents($url);
            $file = str_replace("tmp_title", input("code_title"), $file);
            $file = str_replace("tmp_controller", $table, $file);
            $th = "";
            $td = "";
            $sql = "select column_name as Field , column_comment as Comments,is_nullable,data_type from information_schema.columns where table_schema ='" . config('database.database') . "' and table_name = '" . config('database.prefix') . $table . "' ;";

            $ret = Db::query($sql);
            for ($i = 0; $i < count($ret); $i++) {
                if (in_array($ret[$i]['Field'], [$table . "_id", $table . "_status", $table . "_createtime", $table . "_updatetime"])) {
                    continue;
                } else {
                    $th .= '<th><div class="layui-table-cell "><span>' . (isset($ret[$i]['Comments']) ? $ret[$i]['Comments'] : $ret[$i]['Field']) . '</span></div></th>';
                    $td .= '<td><div class="layui-table-cell">{{item.' . $ret[$i]['Field'] . '}}</div></td>';
                }
            }

            $file = str_replace("tmp_th", $th, $file);
            $file = str_replace("tmp_td", $td, $file);
            $file = str_replace("tmp_controller", $table, $file);
            //print_r($file);exit;
            $myfile = fopen("application/admin/view/" . $table . "/index.html", "w") or die("Unable to open file!");
            fwrite($myfile, $file);
            fclose($myfile);
            //结束生成index

            //开始生成update
            $url = "application/admin/.templateUpdate";
            //echo $url;exit;
            $file = file_get_contents($url);
            $file = str_replace("tmp_title", input("code_title"), $file);
            $file = str_replace("tmp_controller", $table, $file);
            $sql = "select column_name as Field , column_comment as Comments,is_nullable,data_type from information_schema.columns where table_schema ='" . config('database.database') . "' and table_name = '" . config('database.prefix') . $table . "' ;";

            $ret = Db::query($sql);
            $form = "";
            for ($i = 0; $i < count($ret); $i++) {
                if (in_array($ret[$i]['Field'], $this->postBlackList)) {
                    continue;
                }
                $form .= '
                    <div class="layui-form-item">
                        <label class="layui-form-label">' . (isset($ret[$i]['Comments']) ? $ret[$i]['Comments'] : $ret[$i]['Field']) . '</label>
                        <div class="layui-input-block">
                            <input type="text" placeholder="请输入' . (isset($ret[$i]['Comments']) ? $ret[$i]['Comments'] : $ret[$i]['Field']) . '" class="layui-input" v-model="item.' . $ret[$i]['Field'] . '">
                        </div>
                    </div>';
            }
            $file = str_replace("tmp_form", $form, $file);
            $file = str_replace("tmp_controller", $table, $file);
            $myfile = fopen("application/admin/view/" . $table . "/update.html", "w") or die("Unable to open file!");
            fwrite($myfile, $file);
            fclose($myfile);
            //结束生成update
            //开始生成add
            $url = "application/admin/.templateAdd";
            //echo $url;exit;
            $file = file_get_contents($url);
            $file = str_replace("tmp_title", input("code_title"), $file);
            $file = str_replace("tmp_controller", $table, $file);

            $sql = "select column_name as Field , column_comment as Comments,is_nullable,data_type from information_schema.columns where table_schema ='" . config('database.database') . "' and table_name = '" . config('database.prefix') . $table . "' ;";

            $ret = Db::query($sql);
            $form = "";
            for ($i = 0; $i < count($ret); $i++) {
                if (in_array($ret[$i]['Field'], $this->postBlackList)) {
                    continue;
                }
                $form .= '
                    <div class="layui-form-item">
                        <label class="layui-form-label">' . (isset($ret[$i]['Comments']) ? $ret[$i]['Comments'] : $ret[$i]['Field']) . '</label>
                        <div class="layui-input-block">
                            <input type="text" placeholder="请输入' . (isset($ret[$i]['Comments']) ? $ret[$i]['Comments'] : $ret[$i]['Field']) . '" class="layui-input" v-model="item.' . $ret[$i]['Field'] . '">
                        </div>
                    </div>';
            }
            $file = str_replace("tmp_form", $form, $file);
            $file = str_replace("tmp_controller", $table, $file);
            //print_r($file);exit;
            $myfile = fopen("application/admin/view/" . $table . "/add.html", "w") or die("Unable to open file!");
            fwrite($myfile, $file);
            fclose($myfile);
            //结束生成add
        }
        return jok();
    }
}
